package com.jic.weamop.weBankAMOP.callback;

import com.alibaba.fastjson.JSON;
import com.jic.weamop.weBankAMOP.common.dto.BaseMessage;
import org.bcos.channel.client.ChannelPushCallback;
import org.bcos.channel.dto.ChannelPush;
import org.bcos.channel.dto.ChannelResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一回调处理
 * 
 * @author v_wbgyang
 *
 */
public class PushCallback extends ChannelPushCallback {
	//日志记录
	private static Logger logger = LoggerFactory.getLogger(PushCallback.class);
	// 统一回调处理
	private Map<String, TranscationCallBack> callBackMap = new HashMap<String, TranscationCallBack>();

	private static DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	// onPush方法，在收到AMOP消息时被调用
	@Override
	public void onPush(ChannelPush push) {
		// 回包消息
		ChannelResponse response = new ChannelResponse();
		//消息解析
		String jsonstr=push.getContent();//获取消息内容
		logger.info("收到监听消息{}",jsonstr);
		BaseMessage baseMessage= JSON.parseObject(jsonstr, BaseMessage.class);
		String fromId=baseMessage.getFromOrgId();//获取发送机构
		logger.debug("recevie message from {}",fromId);
		//根据发送结构获取业务处理对象
		TranscationCallBack callBack = callBackMap.get(fromId);
		if(callBack==null){
			logger.debug("no callBack service for {},callBack is null ",fromId);
			response.setErrorMessage("fail");
			response.setContent("no callBack service for "+fromId);
		}else{
			doCallBack(response, baseMessage, callBack);
			if(response.getContent()==null){//如果没有设置则返回""
				response.setContent("");
			}
			response.setErrorMessage("succ");
		}
		response.setErrorCode(0);
		push.sendResponse(response);
	}

	private void doCallBack(ChannelResponse response, BaseMessage baseMessage, TranscationCallBack callBack) {
		String messageId = baseMessage.getMessageId();//获取消息Id
		String message = baseMessage.getMessgeBody();//获取消息体
		String serviceId=baseMessage.getServiceId();//获取业务编号
		boolean async=baseMessage.isAsync();//同异步处理
		logger.debug(df.format(LocalDateTime.now()) + "server:request messageId:{}, messgeBody:{},async:{}", messageId,message,async);
		if(async){//同步处理
			callBack.callBack(serviceId,message,response);//相应的业务处理
		}else{//异步处理
			new Thread(new Runnable() {
				public void run() {
					// TODO Auto-generated method stub
					try{
						callBack.callBack(serviceId,message,response);//相应的业务处理	
					}catch(Exception e){
						e.printStackTrace();
						logger.debug("doCallBack to callBack is exception : {}",e.getMessage());
					}
				}
			}).start();
		}
	}

	public Map<String, TranscationCallBack> getCallBackMap() {
		return callBackMap;
	}

	public void setCallBackMap(Map<String, TranscationCallBack> callBackMap) {
		this.callBackMap = callBackMap;
	}
	
	
	
}
